package com.quickcancellation.crm.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.commons.collections4.MapUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ExcelExportUtil {

    /**
     * 导出 Excel 文件
     *
     * @param response  HttpServletResponse
     * @param list      数据列表
     * @param fileName  文件名
     * @param sheetName 工作表名
     * @param headers   标题头数组
     * @throws IOException
     */
    public static void export(HttpServletResponse response, List<Map<String, Object>> list, String fileName, String sheetName, String[] headers) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 生成工作表配置
        Sheet sheet = new Sheet(1, 0);
        sheet.setSheetName(sheetName);

        // 生成表头
        List<List<String>> headList = new ArrayList<>();
        List<String> headTitleList = new ArrayList<>();
        for (String header : headers) {
            headTitleList.add(header);
        }
        headList.add(headTitleList);

        // 生成表格数据
        List<List<Object>> dataList = new ArrayList<>();
        for (Map<String, Object> data : list) {
            List<Object> rowList = new ArrayList<>();
            for (String header : headers) {
                rowList.add(MapUtils.getObject(data, header));
            }
            dataList.add(rowList);
        }

        // 写入 Excel
        EasyExcel.write(outputStream).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).head(headList).sheet(sheet.getSheetName())
                .table(new Table(1).getTableNo()).doWrite(dataList);

        outputStream.flush();
        outputStream.close();
    }
}
